package com.test.mywebtest.jhgd.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * 计算文件的 MD5 哈希值
     *
     * @return MD5 哈希值
     */
    public static String computeFileMD5(InputStream fis) {
        try {
            // 获取 MessageDigest 实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 创建 FileInputStream 对象
            //FileInputStream fis = new FileInputStream(filePath);

            // 缓冲区大小
            byte[] buffer = new byte[8192];
            int numRead;

            // 分块读取文件内容并更新 MessageDigest 对象
            while ((numRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, numRead);
            }

            // 关闭文件输入流
            fis.close();

            // 完成哈希计算并获取结果
            byte[] digest = md.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            throw new RuntimeException("Error computing MD5: " + e.getMessage(), e);
        }
    }


    public static String getByteMD5 (byte[] bytes){
        try {
            // 获取 MD5 消息摘要实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算 MD5 哈希值
            byte[] md5Hash = md.digest(bytes);

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : md5Hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.err.println("无法找到 MD5 算法: " + e.getMessage());
        }
        return "";
    }

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt";
        //String md5Hash = computeFileMD5(filePath);
        //System.out.println("MD5 Hash: " + md5Hash);
    }
}
